using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Data.OleDb;
using System.Collections;

namespace Biokey01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
        private System.Timers.Timer showpicture = new System.Timers.Timer();

        bool isConnected;
         int FMatchType;
        int fpcHandle;
        int time = 0;
        int i = 3;

        object VerTemplate;
        object RegTemplate;
        string RegTemplateStr;
        string izkfpver;

        private void button2_Click(object sender, EventArgs e)
        {
            if (rdb10.Checked)
            {
                axZKFPEngX1.FPEngineVersion = "10";                
            }
            else
                axZKFPEngX1.FPEngineVersion = "9";
            izkfpver = axZKFPEngX1.FPEngineVersion;
            axZKFPEngX1.SensorIndex = 0;
            if (axZKFPEngX1.InitEngine() == 0)
            {
                fpcHandle = axZKFPEngX1.CreateFPCacheDB();
                statusBar1.Panels[1].Text = "Sensor Connected!";

                txtb1.Text = axZKFPEngX1.SensorCount.ToString();
                txtb2.Text = axZKFPEngX1.SensorIndex.ToString();
                txtb3.Text = axZKFPEngX1.ImageWidth.ToString();
                txtb4.Text = axZKFPEngX1.ImageHeight.ToString();
                txtb5.Text = axZKFPEngX1.SensorSN;

                FMatchType = 0;
                isConnected = true;
                btnCloseSensor.Enabled = true;
                //groupBox5.Enabled = true;
                //groupBox3.Enabled = true;
            }
            else
            {
                txtb1.Text = "";
                txtb2.Text = "";
                txtb3.Text = "";
                txtb4.Text = "";
                txtb5.Text = "";
                isConnected = false;
                btnCloseSensor.Enabled = false;
            }

        }


 
        private void btnCloseSensor_Click(object sender, EventArgs e)
        {
            axZKFPEngX1.CancelEnroll();
            axZKFPEngX1.EndEngine();
            //btnCloseSensor.Enabled = false;
            //groupBox5.Enabled = false;
            //groupBox3.Enabled = false;
        }

        private void btnbrowse_Click(object sender, EventArgs e)    //save FP image
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            Cursor = Cursors.WaitCursor;
            saveFileDialog1.FileName = "template";
            saveFileDialog1.Filter = "";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                if (radioButton1.Checked)
                    axZKFPEngX1.SaveBitmap(saveFileDialog1.FileName + ".bmp");
                else
                    axZKFPEngX1.SaveJPG(saveFileDialog1.FileName + ".jpg");
                MessageBox.Show("Save Success", "Warn", MessageBoxButtons.OK);
                Cursor = Cursors.Default;
            }
            else
            {
                Cursor = Cursors.Default;
                return;
            }
        }


        private void button2_Click_1(object sender, EventArgs e)
        {
            if (isConnected)
            {
                if (axZKFPEngX1.IsRegister)
                {
                    axZKFPEngX1.CancelEnroll();
                }
                axZKFPEngX1.EnrollCount = 3;                
                axZKFPEngX1.BeginEnroll();
                time = 1;
            }
            else
                MessageBox.Show("No sensor connected", "error");
        }


        private void btnVerify_Click(object sender, EventArgs e)
        {
            if (txtbThreshold1.Text == "" || txtbThrehold2.Text == "")
            {
                MessageBox.Show("The 1:1Threhold and the 1:N Threhold can not be null!", "error!");
                return;
            }

            if (axZKFPEngX1.IsRegister)
            {
                axZKFPEngX1.CancelEnroll();
            }

            if (radioButton3.Checked)
            {
                FMatchType = 1;
            }
            else
            {
                FMatchType = 2;
            }
            axZKFPEngX1.BeginCapture();
        }


        private void axZKFPEngX1_OnCapture(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnCaptureEvent e)
        {
            VerTemplate = e.aTemplate;
            byte[] vertemplat = (byte[])VerTemplate;
            int score =9;
            int processedFPNumber = 1;
            int ID;
            string tempstr;
            string Template = axZKFPEngX1.GetTemplateAsString();
            if (e.actionResult)
            {
                bool ddd = false;
                string temp;
                int fingerid = 0;
                if (txtfpID.Text == "")
                    fingerid = 0;
                else
                fingerid = Convert.ToInt32(txtfpID.Text);
                axZKFPEngX1.OneToOneThreshold = Convert.ToInt32(txtbThreshold1.Text);
                axZKFPEngX1.Threshold = Convert.ToInt32(txtbThrehold2.Text);
                temp = axZKFPEngX1.GetTemplateAsString();
                if (FMatchType == 1)
                {
                    try
                    {
                        FileStream stream1 = new FileStream(txtPass.Text.Trim() + "/" + txtfpID.Text.Trim() + ".dat", FileMode.OpenOrCreate, FileAccess.Read);
                        byte[] tmpbyte = File.ReadAllBytes(txtPass.Text.Trim() + "/" + txtfpID.Text.Trim() + ".dat");
                        object fuck = tmpbyte;
                        if (axZKFPEngX1.VerFinger(ref fuck, vertemplat, false, ref ddd))    //Σ‘ΆΘΙρΣΝ 
                        //if (axZKFPEngX1.VerFingerFromStr(ref Template, temp, false, ref ddd))
                        {
                            tempstr = "Verify 1:1 Success! FingerNum is " + fingerid.ToString();
                            statusBar1.Panels[2].Text = tempstr;
                        }
                        else
                        {
                            statusBar1.Panels[2].Text = "1:1 Verfy fail!";
                        }
                        Template = "";
                    }
                    catch
                    {
                        statusBar1.Panels[2].Text = "no such a number template!";
                    }

                    
                    
                }
                    if (FMatchType == 2)
                    {
                        ID = axZKFPEngX1.IdentificationInFPCacheDB(fpcHandle, VerTemplate, ref score, ref processedFPNumber);
                        if (ID > 0)
                        {
                            tempstr = "1:N Verify success! fingerID:" + ID.ToString() + "  processedFPNumber is:" + processedFPNumber.ToString();
                            statusBar1.Panels[2].Text = tempstr;
                        }
                        else
                            statusBar1.Panels[2].Text = "1:N Verify fail!";
                    }

                

            }

        }

        private void axZKFPEngX1_OnEnroll(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnEnrollEvent e)
        {
            int i = 0;
            if (e.actionResult)
            {
                RegTemplate = e.aTemplate;
                byte[] tmp = new byte[0];
                tmp =(byte[]) e.aTemplate;

                string sse;
                axZKFPEngX1.AddRegTemplateToFPCacheDB(fpcHandle, Convert.ToInt32(txtbIndex.Text), e.aTemplate);
                saveFileDialog1.Filter = "*.dat|*.dat";
                saveFileDialog1.FileName ="./template data/"+ txtbIndex.Text.Trim()+".dat";
                File.WriteAllBytes(saveFileDialog1.FileName, tmp);
            }
        }

        private void axZKFPEngX1_OnImageReceived(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnImageReceivedEvent e)
        {
            Graphics g = pictureBox1.CreateGraphics();
            int dc = g.GetHdc().ToInt32();
            axZKFPEngX1.PrintImageAt(dc, 0, 0, pictureBox1.Width, pictureBox1.Height);
            showpicture.Interval = 100;
            showpicture.Start();
        }




        private void axZKFPEngX1_OnFeatureInfo(object sender, AxZKFPEngXControl.IZKFPEngXEvents_OnFeatureInfoEvent e)
        {
            string strTemp="FP Quality:";
            if (e.aQuality == 0)
            {
                strTemp = strTemp + "Qualified";
            }
            else
            {
                if (e.aQuality == 1)
                {
                    strTemp = strTemp + "Feature points not enough";
                }
                else
                    strTemp = strTemp + "Unqualified";
            }
            if (axZKFPEngX1.IsRegister)
                if (axZKFPEngX1.EnrollIndex != 1)
                    //strTemp := strTemp + #13+ 'Register status: still press finger ' + IntToStr(ZKFPEngX1.EnrollIndex-1) + ' time!';
                    strTemp = strTemp + "\r\n finger enroll:press finger " + (axZKFPEngX1.EnrollIndex - 1).ToString() + " times again";
                else
                    strTemp = strTemp + "\r\n finger enroll: success enroll";
            statusBar1.Panels[2].Text = strTemp;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            showpicture.Elapsed += new System.Timers.ElapsedEventHandler(showpicture_Elapsed);
        }

        void showpicture_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                Graphics g = pictureBox1.CreateGraphics();
                int dc = g.GetHdc().ToInt32();
                axZKFPEngX1.PrintImageAt(dc, 0, 0, pictureBox1.Width, pictureBox1.Height);
            }
            catch
            {
            }
        }

         ~Form1()
        {
            showpicture.Elapsed -= new System.Timers.ElapsedEventHandler(showpicture_Elapsed);
        }

         private void btnselect_Click(object sender, EventArgs e)
         {
             openFileDialog1.Filter = "*.dat|*.dat";
            openFileDialog1.FileName = "./";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filepaths = Directory.GetCurrentDirectory();
                txtPass.Text = filepaths;
            }
         }

         private void button1_Click(object sender, EventArgs e)
         {
             string path = txtPass.Text.Trim();
             string[] files = Directory.GetFiles("./template data", "*.dat*");
             if (files.Length != 0)
             {
                 foreach (string filename in files)
                 {
                     FileInfo inf = new FileInfo(filename);
                     string name = inf.Name;
                     int ddd = name.IndexOf('.');
                     string fingerid= name.Remove(ddd);
                     FileStream stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Read);
                     byte[] buffer = File.ReadAllBytes(filename);
                     axZKFPEngX1.AddRegTemplateToFPCacheDB(fpcHandle, Convert.ToInt32(fingerid), buffer);
                 }
             }
         }

     }

}
    
